package binghua.network;

import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailOps {
	/**
	 * TODO: Not Tested yet!!!!!
	 * Send an email.
	 * @param smtpHost
	 *            "smtp.gmail.com"
	 * @param smtpPort
	 *            "465"
	 * @param sendFrom
	 * @param sendTo
	 * @param subject
	 * @param bodyText
	 * @param attachs
	 * @throws MessagingException
	 * @throws AddressException
	 */
	public static void sendEmail(final String smtpHost, final String smtpPort,
			final String sendFrom, final String sendTo, final String subject,
			final String bodyText, final String[] attaches,
			final String password) throws AddressException, MessagingException {

		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		Properties props = new Properties();
		props.put("mail.smtp.host", smtpHost);
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", smtpPort);
		props.put("mail.smtp.socketFactory.port", smtpPort);
		props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
		props.put("mail.smtp.socketFactory.fallback", "false");

		Session session = Session.getDefaultInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(sendFrom, password);
					}
				});

		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(sendFrom));
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(
				sendTo));
		message.setSubject(subject);
		message.setSentDate(new Date());

		MimeBodyPart messagePart = new MimeBodyPart();
		messagePart.setText(bodyText);

		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(messagePart);

		for (String attach : attaches) {
			MimeBodyPart attachmentPart = new MimeBodyPart();
			FileDataSource fileDataSource = new FileDataSource(attach) {
				public String getContentType() {
					return "application/octet-stream";
				}
			};
			attachmentPart.setDataHandler(new DataHandler(fileDataSource));
			attachmentPart.setFileName(attach);
			multipart.addBodyPart(attachmentPart);
		}
		message.setContent(multipart);
		Transport.send(message);
	}
}